﻿using DG.Tweening;
using UnityEngine;
using UnityEngine.EventSystems;

public class GreenVegetableController : EventBehaviour {
    public float burstForce = 1.2f;

    Transform _transform;
    bool _isDraging;

	void Start () {
        _transform = GetComponent<Transform>();
        TargetSlicer.Instance.onIgnoreSliceCallback += OnSliced;
    }

    void OnDestroy() {
        if (TargetSlicer.HasInstance()) {
            TargetSlicer.Instance.onIgnoreSliceCallback -= OnSliced;
        }
    }

    public override void OnPointerEnter(PointerEventData eventData) {
        if (_isDraging == false) {
            _isDraging = true;
        }
    }

    void ApplyForce(Rigidbody body) {
        body.AddForce(Vector3.up * burstForce, ForceMode.Impulse);
    }

    void OnSliced() {
        if (DragAndClickTrigger.IsDraging || _isDraging == false) {
            return;
        }

        _isDraging = false;
        AudioManager.Instance.PlaySound(ChineseRestaurantResPath.SFX_FOOD_SLICE);
        var rb = _transform.GetComponentInChildren<Rigidbody>();

        if (rb) {
            rb.transform.SetParent(_transform.parent);
            rb.isKinematic = false;
            ApplyForce(rb);

            if (_transform.GetComponentInChildren<Rigidbody>() == null) {
                _transform.DOLocalMoveY(2f, 1f).OnComplete(OnFinished);
            }
        } else {
            _transform.DOLocalMoveY(2f, 1f).OnComplete(OnFinished);
        }
    }

    int _leaves = 5;

    void OnFinished() {
        TargetSlicer.Instance.sampleCount = _leaves;
        Destroy(gameObject);
    }
}
